<template>
	<view>
		<view class="padding-all-20">上传图片</view>
		<view style="padding:0 20rpx;">
			<view class="row" style="flex-wrap: wrap;">
				<view class="" v-for="(item, index) in fileList" :key="index"
					style="position: relative; height: 330rpx;width: calc((100% - 40rpx) / 3);margin-bottom: 20rpx;;background-color: #e1e1e1;"
					:style="[{marginRight:(index + 1 ) % 3 != 0? '20rpx': '0'}]">
					<view class="absolute top right fs-20"
						style="background-color: rgba(0,0,0,0.4);color: #fff;padding: 5rpx 8rpx;" v-if="item"
						@click="onEditorImage(item, index)">
						编辑
					</view>
					<image :src="item" mode="widthFix" style="width: 100%;height: 100%;"></image>
					<view class="" v-if="index == 0"
						style="position: absolute; right: 0; bottom:0; width: 70rpx;height: 70rpx;background: gold;clip-path: polygon(100% 0%, 0 100%, 100% 100%);">
						<text class="absolute bottom fs-20" style="right: 7rpx;">封面</text>
					</view>
				</view>
				<view class="column-center"
					style="height: 330rpx;width: calc((100% - 40rpx) / 3);background-color: #e1e1e1;"
					v-if="fileList.length < 9" @click="onUploadImages()">
					<uni-icons type="plusempty" size="26"></uni-icons>
					<view class="fs-26 marginTop-20">添加形象照</view>
				</view>
			</view>
		</view>
		<button v-if="isUpload" class="sub-btn" @click="savePhoto">保存</button>
		<button v-else class="sub-btn" @click="backHomePage">保存</button>

		<view class="relative left right bottom top" style="z-index:99999;background-color:#000;" v-show="isShowTailor">
			<jp-cropper-watermark mode="free" :width="270" :height="398" :maxWidth="1024" :maxHeight="1024"
				:url="TailorSrc" @cancel="isShowTailor = false" @ok="onSubmitTailor"></jp-cropper-watermark>
		</view>
		<fui-actionsheet :show="bottomFunction.show" :maskClosable="true" :itemList="itemList"
			@cancel="bottomFunction.show = false" @click="onFunction"></fui-actionsheet>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				UserID: 0,
				itemList: [{
						text: '设置为封面',
					},
					{
						text: '替换',
					},
					{
						text: '删除',
					},
				],
				uploadUrl: 'https://api.meimo.comdns.cn/common/Upload/upload?file=userphoto&type=image',
				uploadStatus: {},
				fileList: [],
				uploadUrls: [],
				TailorSrc: "",
				isShowTailor: false,
				isCutting: false,
				mokaInfoNav: 0,
				successImageList: [],
				bottomFunction: {
					show: false
				},
				coverFunction: {
					imageItem: {},
					imageIndex: 0
				},
				// 下标为 0 的为封面
				setCoverIndex: 0,
				// 判断是否为替换
				isReplace: false,

				timer: null,
				isUpload: true
			};
		},
		onLoad(prmams) {
			// 判断是否时从我的模卡资料跳转过来的
			// console.log("prmams",prmams)
			this.mokaInfoNav = prmams.mokaInfoNav ? prmams.mokaInfoNav : 0
			this.getPhoto();
		},
		onShow() {
			this.isShowTailor = true;
			// this.debounce(this.onSubmitTailor, 2000)
		},
		// 存到一个数组内，依次判断上一个图片是否裁剪，如果裁剪玩给一个标示，准备裁剪下一张知道length 为0关闭
		// 没点击一个裁剪完就删掉一个根据再次点击删下一个
		methods: {
			async onFunction(event) {
				if (event.index == 0) {
					await this.onSetCover();
				}
				if (event.index == 1) {
					await this.onReplaceImage();
				}
				if (event.index == 2) {
					await this.onDeleteImage();
				}
				await this.savePhotoOK()
				// console.log(event)

			},
			onEditorImage(imageItem, imageIndex) {
				this.bottomFunction.show = true;
				this.coverFunction.imageItem = imageItem;
				this.coverFunction.imageIndex = imageIndex;

			},
			// 设置封面
			onSetCover() {
				// 接收图片 index 值
				this.setCoverIndex = this.coverFunction.imageIndex;
				this.bottomFunction.show = false;
			},

			// 替换图片
			onReplaceImage() {
				// 确定为替换
				this.isReplace = true;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: res => {
						// console.log('tempFilePaths', res.tempFilePaths)

						// 接收单张图片
						this.TailorSrc = res.tempFilePaths[0]

						// console.log('this.TailorSrc', this.TailorSrc)
						// console.log('this.fileList.length', this.fileList)
						if (this.TailorSrc != '') this.isShowTailor = true

						this.bottomFunction.show = false;

					}
				})
			},

			// 删除
			onDeleteImage() {
				// 如果删除的是选定封面的哪一张图片，设定为第一张为封面
				if (this.setCoverIndex == this.coverFunction.imageIndex) this.setCoverIndex = 0

				this.fileList.splice(this.coverFunction.imageIndex, 1)

				this.bottomFunction.show = false;
			},

			// 上传多张图片
			onUploadImages() {
				let count = this.fileList.length != 0 ? 9 - this.fileList.length : 9;
				uni.chooseImage({
					count: count,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: res => {
						console.log('tempFilePaths', res.tempFilePaths)

						// 接收单张图片
						// this.TailorSrc = res.tempFilePaths[0]
						// if (this.TailorSrc != '') this.isShowTailor = true
						// return;
						// 接受图片列表
						this.successImageList = res.tempFilePaths

						// 首次赋值
						this.TailorSrc = this.successImageList[0]
						// console.log('this.TailorSrc', this.TailorSrc)
						// console.log('this.fileList.length', this.fileList)
						if (this.TailorSrc != '') this.isShowTailor = true
					},
					fail: (err) => {
						// console.log(err)
					}
				})
			},

			uploadImage(tmpFile) {
				this.isUpload = true;
				uni.showLoading({
					title: '上传中'
				})
				return new Promise((reslove, reject) => {
					uni.uploadFile({
						url: 'https://api.meimo.comdns.cn/common/Upload/upload?file=uniapp&type=image', //仅为示例，非真实的接口地址
						filePath: tmpFile,
						name: "file",
						formData: {},
						success: (uploadFileRes) => {
							reslove(this.$baseUrl + JSON.parse(uploadFileRes.data).fileName)

						}
					})
				})
			},
			getPhoto() {
				this.$httpost('/UserAction/getMyPhoto', {}).then(res => {
					if (res.code == 200) {
						// console.log('11111111接口触发了')
						if (JSON.parse(res.data.UserPhotos) != null) {
							this.UserID = res.data.UserID
							this.uploadUrls = JSON.parse(res.data.UserPhotos)
							this.fileList = this.uploadUrls

							// this.setCoverIndex = res.data.UserPhotosIndex;
						}
					}
				});
			},
			// 确定剪切
			onSubmitTailor(filPath) {

				console.log('裁剪结果', filPath);

				if (this.timer) {
					clearTimeout(this.timer);
					// return false;
				}
				// console.log('this.timer', this.timer)
				this.timer = setTimeout(async () => {
					// 处理点击事件
					// console.log('点击事件被触发');
					// 这里可以放置点击后需要执行的代码

					if (!this.isReplace) {
						// 如果不是点击替换 则上传多张
						// console.log('判断isReplace')
						if (this.successImageList.length !== 0) {
							// console.log('判断successImageList')
							// 取当前裁剪数据的下标
							let successImageListIndex = this.successImageList.indexOf(this.TailorSrc);

							this.fileList.push(await this.uploadImage(filPath.path));
							// 删除当前已经裁剪过的图片
							this.successImageList.splice(successImageListIndex, 1);

							// 重新赋值裁剪
							this.TailorSrc = this.successImageList[0];
							uni.hideLoading();
							if (this.successImageList.length === 0) return this.isShowTailor = false;
						}
					} else {
						// 已经点击替换，更换一张
						// console.log('走替换这了')

						// 替换图片 coverImage
						// let coverImage = await this.uploadImage(filPath)

						// 更换图片
						this.fileList.splice(this.coverFunction.imageIndex, 1, await this.uploadImage(filPath
							.path))
						console.log(this.fileList, '	this.fileList');

						// 替换之后改为初始状态
						this.isReplace = false

						uni.hideLoading();
						this.isShowTailor = false
					}

					// 清除定时器
					this.timer = null;
				}, 1000);



				// // console.log('this.fileList ', this.fileList)
				// // console.log('已经没有图片了')
			},
			backHomePage() {
				if (this.fileList.length < 3) {
					uni.showToast({
						title: '形象照片不能少于三张哦~',
						icon: 'none'
					})
					return
				}

				if (this.mokaInfoNav == 1) {
					uni.navigateBack({
						delta: 1
					});
					return;
				}
				uni.redirectTo({
					url: '/myPages/pages/mypage?artisterID=' + this.UserID
				});

			},
			savePhotoOK() {
				// // console.log('this.uploadUrls', this.fileList);
				// return;
				// 暂时注释
				console.log('替换走这里了吗？');
				if (!this.isReplace) {
					this.isUpload = false;
				} else {
					this.isUpload = true;
				}
				this.upImg(this.fileList)
			},
			// 只是 进行  设置封面  删除操作
			upImg(uploadUrls) {
				if (uploadUrls.length == this.fileList.length && uploadUrls.length >= 3) {
					uni.hideLoading()
					this.$httpost('/UserAction/saveMyPhoto', {
						uploadUrls: uploadUrls,
						uploadIndex: this.setCoverIndex
					}).then(res => {
						if (res.code == 200) {
							this.setCoverIndex = 0
							this.getPhoto()
						}
					});
				}
			},

			onUpImg(uploadUrls) {
				if (this.fileList.length < 3) {
					uni.showToast({
						title: '形象照片不能少于三张哦~',
						icon: 'none'
					})
					return
				}

				if (uploadUrls.length == this.fileList.length) {
					uni.hideLoading()
					this.$httpost('/UserAction/saveMyPhoto', {
						uploadUrls: uploadUrls,
						uploadIndex: this.setCoverIndex
					}).then(res => {
						if (res.code == 200) {
							this.setCoverIndex = 0
							if (this.mokaInfoNav == 1) {
								uni.navigateBack({
									delta: 1
								});
								return;
							}
							uni.redirectTo({
								url: '/myPages/pages/mypage?artisterID=' + res.data
									.UserID
							});

						}
					});
				}
			},

			savePhoto() {

				// 暂时注释
				if (this.fileList.length < 3) {
					uni.showToast({
						title: '形象照片不能少于三张哦~',
						icon: 'none'
					})
					return false;

				}
				// console.log('this.fileList  savePhoto', this.fileList)
				console.log(this.fileList, 'this.fileList');
				debugger
				this.onUpImg(this.fileList)
			}
		}
	}
</script>

<style lang="scss">
	.submitBtn {

		background-color: $globalColor;
		color: #000;
		font-size: 28rpx;
		border: 0rpx solid $globalColor;
		width: 80vw;
		height: 80rpx;
		line-height: 80rpx;
		margin: auto;
		margin-top: 50rpx;
	}

	.fui-cropper__tabbar {
		/* #ifndef APP-NVUE */
		display: flex;
		z-index: 20;
		position: relative;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		height: 120rpx;
		left: 0;
		right: 0;
		bottom: 0;
		/* #ifdef APP-NVUE */
		border-top: 0.5px solid #666;
		/* #endif */
	}

	/* #ifndef APP-NVUE */
	.fui-cropper__tabbar::before {
		content: ' ';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 1px;
		border-top: 1px solid #666;
		transform: scaleY(0.5);
		transform-origin: 0 0;
		z-index: 21;
	}

	/* #endif */

	.fui-text {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		font-size: 32rpx;
		font-weight: normal;
		color: #fff;
		flex: 1;
		text-align: center;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		line-height: 80rpx;
		/* #ifdef H5 */
		cursor: pointer;
		/* #endif */
	}

	.function-button {
		background-color: #fff;
		font-size: 26rpx;
		height: 100rpx;
		line-height: 100rpx;
	}
</style>